'use strict';
const db = uniCloud.database()
const userDb = db.collection('Accounts')

exports.main = async (event, context) => {
  try {
    console.log('---addUser---event : ', event)
    
    // 校验逻辑
    if (!event.name || event.name.length < 2 || event.name.length > 32) {
      return { code: 400, msg: '账户名需2-32位' }
    }
    if (!event.password || event.password.length < 4 || event.password.length > 32) {
      return { code: 400, msg: '密码需4-32位' }
    }

    // 查重
    const userCheck = await userDb.where({ account: event.name }).get()
    if (userCheck.data.length > 0) {
      return { code: 400, msg: '账户名已存在' }
    }

    // 移除user_id字段
    const userData = {
      account: event.name.trim(),
      password: event.password,
      register_time: new Date(),
      last_login_time: null,
      nickname: (event.nickname || '').trim(),
      mobile: (event.mobile || '').trim(),
      email: (event.email || '').trim()
    }

    let addUserRes = await userDb.add(userData)
    
    return { code: 200, msg: '注册成功', data: addUserRes }
  } catch (err) {
    console.error('---addUser---error : ', err)
    return { code: 500, msg: '注册失败：' + err.message }
  }
};